<template>
  <div class="search">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.push('/')" />

    <van-search
      v-model.trim="inputValue"
      placeholder="请输入搜索关键词"
      @input="inputEvent"
      @search="searchResult(inputValue)"
      show-action>
      <template #action>
        <span @click="searchResult(inputValue)">搜索</span>
      </template>
    </van-search>

    <van-cell-group v-if="!inputValue">
      <van-cell title="历史记录"></van-cell>
      <van-cell
        :title="i"
        v-for="(i, index) in historyList"
        :key="index"
        @click="searchResult(i)" />
    </van-cell-group>
    <van-cell-group v-else>
      <van-cell v-for="(item, index) in list" :key="index">
        <template #title>
          <div v-html="item.str" @click="searchResult(item.key)"></div>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>
<script>
import { suggestion } from '@/api/search'
import { deFn } from '@/utils/index'
export default {
  data () {
    return {
      inputValue: '',
      list: [],
      interval: 0,
      historyList: JSON.parse(localStorage.getItem('historyList')) || []
    }
  },
  methods: {
    inputEvent: deFn(async function (v) {
      if (v === '') {
        return
      }
      const res = await suggestion({
        q: v
      })
      if (res.data.data.options[0] === null) {
        this.list = []
      } else {
        this.list = res.data.data.options.map(item => {
          const reg = new RegExp(this.inputValue, 'ig')
          const str = item.replace(
            reg,
            `<span style="color:red;">${this.inputValue}</span>`
          )
          return {
            str: str,
            key: item
          }
        })
      }
    }, 500),
    searchResult (key) {
      if (!this.historyList.includes(key)) {
        this.historyList.push(key)
        localStorage.setItem('historyList', JSON.stringify(this.historyList))
      }
      this.$router.push('/result?key=' + encodeURIComponent(key))
    }
  }
}
</script>
<style></style>
